<?php

namespace addons\kzvote\controller;

use addons\kzvote\library\WechatService;
use app\common\model\kzvote\gift\Order;
use think\Db;
use think\Log;

class Notify extends Base
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function wxapp(){
        return $this->pay('wxapp');
    }

    public function wechat(){
        return $this->pay('wechat');
    }

    /**
     * 微信支付回调
     */
    public function pay($platform)
    {
        $app      = WechatService::getPayment($platform);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            $out_trade_no = $message['out_trade_no'];
            $money = $message['total_fee'];
            Db::startTrans();
            try {
                if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    // 用户是否支付成功
                    if ($message['result_code'] === 'SUCCESS') {
                        // 统一处理订单回调
                        $order = Order::get(['order_no' => $out_trade_no]);

                        if (!$order) {
                            return $fail('订单不存在');
                        }
                        if ($order['money']*100 != $money){
                            return $fail('订单金额不一致');
                        }
                        $order->status = '20';

                        $vote = \app\common\model\kzvote\Vote::get($order->vote_id);

                        $person = \app\common\model\kzvote\Person::get($order->person_id);

                        $order->save();
                        $vote->setInc('count', $order->num);
                        $person->setInc('count', $order->num);
                        Db::commit();
                    }
                } else {
                    Log::error('订单号：' . $out_trade_no . ',' . json_encode($message));
                    $fail('通信失败，请稍后再通知我');
                }
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('订单号：' . $out_trade_no . ',' . json_encode($message));
                $fail('通信失败，请稍后再通知我');
            }
            return true;
        });

        $response->send();
    }


}
